package tech.jabari.user.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import tech.jabari.utils.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static tech.jabari.constants.UMSConstant.VERIFY_CODE;

/**
 * 用户注册的处理。
 * @author Jabari Lu
 * @title: UserRegister
 * @data 2020/7/29 11:08
 */
@WebServlet("/userRegister")
public class UserRegister extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("------doGet()");
        resp.getWriter().write("<h1>GET</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("---------doPost().... ");
        // 将map转换为json格式的字符串传给前端。
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();
        //1.获取用户输入的用户名：username
        //设置请求的编码格式
        req.setCharacterEncoding("UTF-8");
        String characterEncoding = req.getCharacterEncoding();
        System.out.println("req characterEncoding = " + characterEncoding);
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String sex = req.getParameter("sex");
        String birth = req.getParameter("birth");// null

        //获取用户输入的验证码
        String code = req.getParameter("code");
        // 获取session中保存的正确的验证码。
        HttpSession session = req.getSession();
        Object verifyCodeObj = session.getAttribute(VERIFY_CODE);
        if (verifyCodeObj != null) {
            String verifyCode = verifyCodeObj.toString();
            if (!verifyCode.equalsIgnoreCase(code)) {
                map.put(VERIFY_CODE,"-1");
                String ret = objectMapper.writeValueAsString(map);
                resp.getWriter().write(ret);
                return;
            } else {
                map.put(VERIFY_CODE,"1");
            }
        }

        // ""  -> null
        if ("".equals(birth)) {
            birth = null;
        }
        System.out.println("username = " + username);
        System.out.println("pwd = " + pwd);

        //2.将用户信息保存到MySQL
        saveUser(username,pwd,email,phone,sex,birth);

        //设置响应编码
//        resp.setContentType("text/html;charset=UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //3.给浏览器返回一个响应
//        resp.getWriter().write("<h1>恭喜用户：【" + username+"】注册成功！</h1>");


        // 将map转换为json格式的字符串传给前端。
        String ret = objectMapper.writeValueAsString(map);
        resp.getWriter().write(ret);
    }


    /**
     * 保存用户信息到MySQL数据库。
     * @param params
     */
    public void saveUser(String ...params) {
        System.out.println("UserRegister.saveUser()............");
        JdbcUtil.getConnection();
        String sql = "insert into t_user(username,pwd,email,phone,sex,birth)values(?,?,?,?,?,?)";
        JdbcUtil.update(sql, params);
        /*JdbcUtil.close();*/
        // 此处不可以关闭Connection对象，因为它是static的，
        // 后面的查询等操作还要使用Connection对象。
    }
}
